//
//  NCCameraManager.m
//  Camera
//
//  Created by Neusoft on 11-7-15.
//  Copyright 2011 Neusoft. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>

#import "NCBarButton.h"
#import "NCCameraManager.h"
#import "UIColor-Expanded.h"
#import <ImageIO/ImageIO.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "TravelException.h"
#import "UIImage+Extends.h"


#define kFilterBarScrollViewTag             777
#define kFilterBarScrollViewSubViewTag      888
#define kAlertViewTag4DownloadMotu          999

@interface NCCameraManager (UtilityMethods)
- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center;
@end

@implementation NCCameraManager

@synthesize parentViewController = _parentViewController;
@synthesize allowsImageEditing = _allowsImageEditing;
@synthesize isFromSelfView = _isFromSelfView;
@synthesize delegate = _delegate;
@synthesize image = _image;
@synthesize lat;
@synthesize lng;
@synthesize photoDate;

#define M_PI        3.14159265358979323846264338327950288

#define kProductsViewFrame             CGRectMake(0, UIScreenHeight-90, 320, 90)
#define kToolBarImageFrame             CGRectMake(0, UIScreenHeight-53, 320, 53)		       
#define kScrollViewFrame               CGRectMake(0, 0, 320, UIScreenHeight)

#define kProductsBGImage               @"image_effect_bar_bg.png"
#define kRechooseBarBGImage            @"original_navi.png"
#define kToolBarBGImage                @"image_effect_camera_bar.png"
#define kButtonImageFile	           @"image_effect_button_small.png"
#define kselectedButtonImageFile	   @"image_effect_button_small.png"
#define kTakePictureImage              @"image_effect_camera_take.png"

#define kIphone5TopBarImage            @"image_carema_iphone5_top_bar.png"
#define kIphone5barBGImage             @"image_carema_iphone5_bg.png"
#define kIphone5CancelImage            @"image_carema_iphone5_cancel_button.png"
#define kIphone5RetakeButton           @"image_carema_iphone5_retake_button.png"
#define kIphone5PhotoButton            @"image_carema_iphone5_photo_button.png"
#define kIphone5ChooseAlbum            @"image_carema_iphone5_choose_album.png"

#define kPositionLabelTextColorNomal   0xFF9E9E9E
#define kNormalTextColor			   0xAF000000

#define ZOOM_STEP                      1.5
#define ZOOM_VIEW_TAG                  100
#define kDefaultTextFontSize		   13
#define kImageCornerRadius             8
#define kIphone5FileterHeight          /*114*/90
#define kIphone5CameraToolBarHeight    96

#define kOpenImageFail                 @"图片打开失败"
#define kClickRotateImage              @"单 击 可 旋 转 图 片"

#pragma mark -
#pragma mark Override base functions

- (id)initWithParentController:(UIViewController*)viewController isFromSelfView:(BOOL)isFromSelfView
{
    self = [super init];
	if ( self )
	{
		_parentViewController = viewController;
        _isFromSelfView = isFromSelfView;
        
        if (_isFromSelfView)
        {
            _allowsImageEditing = YES;
        }
        
		return self;
        
	}
	return nil;
}

- (id)initWithParentController:(UIViewController*)viewController isFromSelfView:(BOOL)isFromSelfView isEnableEditImage:(BOOL)isEnableEditImage
{
    self = [super init];
	if ( self )
	{
		_parentViewController = viewController;
        _isFromSelfView = isFromSelfView;
        
        _allowsImageEditing = isEnableEditImage;
        
		return self;
        
	}
	return nil;
}

- (void)dealloc
{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_nameArray release];
    _nameArray = nil;
    _picker.delegate = nil;
    [_picker dismissViewControllerAnimatedWithCompatibility:NO];
    [_picker release];
    _picker = nil;
    [_info release];
    _info = nil;
    [_pageScrollView removeObserver:self forKeyPath:@"contentOffset"];
    [_pageScrollView release];
    _pageScrollView = nil;
    self.image = nil;
    
    [super dealloc];
}

+ (BOOL)supportGetPicFromAlbum
{
	return [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum];
}

+ (BOOL)supportGetPicFromCamera
{
	return [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera];
}

- (BOOL)getCameraPictureFromAlbum:(BOOL)fromAlbum withDeviceFrontMode:(BOOL)isFront
{
    _isFromAlbumDetail = YES;
    
    if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera] && !fromAlbum) ||
		([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum] && fromAlbum))
	{
		if (!_parentViewController)
		{
			if ([_delegate respondsToSelector:@selector(returnError:)])
			{
				[_delegate returnError:@"parent view is nil"];
			}
			return NO;
		}
		
		UIImagePickerController *picker = [[[UIImagePickerController alloc] init] autorelease];
		picker.delegate = self;
        
		picker.sourceType = (fromAlbum) ? UIImagePickerControllerSourceTypeSavedPhotosAlbum : UIImagePickerControllerSourceTypeCamera;
        
        _picker.delegate = nil;
        [_picker release];
        _picker = nil;
        _picker = [picker retain];
        if (_isFromSelfView)
        {
            picker.cameraDevice = isFront ? UIImagePickerControllerCameraDeviceFront
            : UIImagePickerControllerCameraDeviceRear;
            
            // 设置允许编辑图片

            picker.allowsEditing = _allowsImageEditing;
        }
        
        //显示自定义toolBar
        picker.showsCameraControls = YES;
        //        [self createToolBar];
        
        [_parentViewController presentViewControllerWithCompatibility:picker animated:YES];
        
		return YES;
	}
	else
	{
		if ([_delegate respondsToSelector:@selector(returnError:)])
		{
			[_delegate returnError:@"Error accessing camera"];
		}
	}
	return NO;
}

- (BOOL)getCameraPictureFromAlbum:(BOOL)fromAlbum
{
	if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera] && !fromAlbum) ||
		([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum] && fromAlbum))
	{
		if (!_parentViewController)
		{
			if ([_delegate respondsToSelector:@selector(returnError:)])
			{
				[_delegate returnError:@"parent view is nil"];
			}
			return NO;
		}
		
		UIImagePickerController *picker = [[[UIImagePickerController alloc] init] autorelease];
		picker.delegate = self;
        
		picker.sourceType = (fromAlbum) ? UIImagePickerControllerSourceTypeSavedPhotosAlbum : UIImagePickerControllerSourceTypeCamera;
        
        _picker.delegate = nil;
        [_picker release];
        _picker = nil;
        _picker = [picker retain];
        if (_isFromSelfView) 
        {
            picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            
            // 设置允许编辑图片

            picker.allowsEditing = _allowsImageEditing;
        }

        //显示自定义toolBar
        picker.showsCameraControls = YES;
//        [self createToolBar];
        
        [_parentViewController presentViewControllerWithCompatibility:picker animated:YES];
        
		return YES;
	}
	else
	{
		if ([_delegate respondsToSelector:@selector(returnError:)])
		{
			[_delegate returnError:@"Error accessing camera"];
		}
	}
	return NO;
}

- (void)selectExistingPictureWithoutAnimation
{
    if ([UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypePhotoLibrary])
	{
		if (!_parentViewController)
		{
			if ([_delegate respondsToSelector:@selector(returnError:)])
			{
				[_delegate returnError:@"parent view is nil"];
			}
			return;
		}
//		isOriginalBar = YES;
//        [[LVFastLauncher sharedInstance] IOSFiveOriginalBackgroud];

        
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        if (_isFromSelfView) {
            picker.allowsEditing = _allowsImageEditing;

        }
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _picker.delegate = nil;
        [_picker release];
        _picker = nil;
        _picker = [picker retain];
        [_parentViewController presentViewControllerWithCompatibility:picker animated:NO];
        [picker release];
    }
    else
	{
        if ([_delegate respondsToSelector:@selector(returnError:)])
		{
			[_delegate returnError:@"Error accessing photo library"];
		}
    }
}

- (void)selectExistingPicture
{	
    if ([UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypePhotoLibrary])
	{
		if (!_parentViewController)
		{
			if ([_delegate respondsToSelector:@selector(returnError:)])
			{
				[_delegate returnError:@"parent view is nil"];
			}
			return;
		}
//		isOriginalBar = YES;
//        [[LVFastLauncher sharedInstance] IOSFiveOriginalBackgroud];
        
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;

		picker.allowsEditing = _allowsImageEditing;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _picker.delegate = nil;
        [_picker release];
        _picker = nil;
        _picker = [picker retain];
        [_parentViewController presentViewControllerWithCompatibility:picker animated:YES];
        [picker release];
    }
    else
	{
        if ([_delegate respondsToSelector:@selector(returnError:)])
		{
			[_delegate returnError:@"Error accessing photo library"];
		}
    }
    
}



- (UIImageView *) imageViewForView: (UIView *) view
{
	UIGraphicsBeginImageContext(view.bounds.size);
	[view.layer renderInContext: UIGraphicsGetCurrentContext()];
	
	UIImageView * result = [[UIImageView alloc] initWithImage: UIGraphicsGetImageFromCurrentImageContext()];
	
    
	UIGraphicsEndImageContext();
	
	return ( [result autorelease] );
}

//- (void) useImage
//{
//    [_picker dismissViewControllerAnimatedWithCompatibility:NO];
////    isOriginalBar = NO;
////    [[LVFastLauncher sharedInstance] IOSFiveDefaultBackground];
//    
//    [self returnTheImage:_selfImageView.image];
//
//    self.image = nil;
//    [_selfImageView removeFromSuperview];
//    _selfImageView = nil;
//    [_selfImageView removeFromSuperview];
//    _selfImageScrollView = nil;
//    if (_noChangeImageView) {
//        [_noChangeImageView release];
//    }
//    _noChangeImageView = nil;
//}









#pragma mark -
#pragma mark self avater changed


//- (BOOL)createImageScrollView:(UIImage *)image
//{
//    if (_selfImageScrollView == nil)
//    {
//        UIScrollView* selfImageScrollView=[[[UIScrollView alloc] initWithFrame:kScrollViewFrame] autorelease];
//        _selfImageScrollView = selfImageScrollView;
//        _selfImageScrollView.backgroundColor = [UIColor blackColor];
//        _selfImageScrollView.delegate = self;
//    }
//
//    if (_selfImageView == nil)
//    {
//        //ytx
//        if (_noChangeImageView == nil) {
//            _noChangeImageView = [[UIImageView alloc] initWithImage:image];
//        }
//        UIImageView *selfImageView = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0,320,UIScreenHeight-160)] autorelease];
//        selfImageView.backgroundColor = [UIColor clearColor];
//        selfImageView.image = image;
//        
//        if (image.size.width > 0 && image.size.height > 0) 
//        {
//            CGRect rect = selfImageView.frame;
//            rect.size.width = image.size.width;
//            rect.size.height =  image.size.height;
//            
//            double widthRate = (double)( 320 / (double)(image.size.width));
//            double heightRate = (double)( UIScreenHeight / (double)(image.size.height));
//            
//            if (widthRate < heightRate) 
//            {
//                rect.size.width = rect.size.width * widthRate;
//                rect.size.height = rect.size.height * widthRate;
//            }
//            else
//            {
//                rect.size.width = rect.size.width * heightRate;
//                rect.size.height = rect.size.height * heightRate;
//            }
//            selfImageView.frame = rect;
//        }
//        else
//        {
//            if (![_selfImageScrollView superview]) {
//                [_selfImageScrollView removeFromSuperview];
//            }
//            _selfImageScrollView = nil;
//            return NO;
//        }
//        
//        selfImageView.center = CGPointMake(320/2, UIScreenHeight/2);
////#ifdef KMoTu
//#if 0 //不需要的代码
//        //        //加旋转
//        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageRota)];
//        gesture.numberOfTapsRequired = 1;
//        gesture.numberOfTouchesRequired = 1;
//        gesture.delegate = self;
//        [_selfImageScrollView setUserInteractionEnabled:YES];
//        [_selfImageScrollView addGestureRecognizer:gesture];
//        [gesture release];
////        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
////
////        [_selfImageScrollView addGestureRecognizer:singleTap];
////        
////        [singleTap release];
//#endif
////        if (_isFromSelfView) 
////        {
////            selfImageView.userInteractionEnabled = YES;
////            
////            [selfImageView setTag:ZOOM_VIEW_TAG];
////            
////            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
////            
////            [selfImageView addGestureRecognizer:singleTap];
////            
////            [singleTap release];             
////        }
//        
//        selfImageView.userInteractionEnabled = YES;
//        
//        [selfImageView setTag:ZOOM_VIEW_TAG];
//        
//        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
//        
//        [selfImageView addGestureRecognizer:singleTap];
//        
//        [singleTap release];
//        
//        [_selfImageScrollView addSubview: selfImageView];
//        _selfImageView = selfImageView;
//    }
//    [_picker.view addSubview:_selfImageScrollView];
//
//     return YES;
//}
//#ifdef KMoTu

#pragma mark 选中某个图片

#define UploadPhotoClipSizePor CGSizeMake(480, 720)
#define UploadPhotoClipSizeLan CGSizeMake(720, 480)



//- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
//
//    NSString *className = [NSString stringWithFormat:@"%@",[viewController class]];
//    if ([className isEqualToString:@"PLUIAlbumViewController"]) {
//        
//        UIImage *theBackgroundImage = [UIImage imageNamed:@"original_navi.png"];
//        theBackgroundImage = [theBackgroundImage resizableImageWithCapInsets:UIEdgeInsetsMake(20, 3, 20, 3)];
//        [navigationController.navigationBar  setBackgroundImage:theBackgroundImage forBarMetrics:UIBarMetricsDefault];
//    }
//}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [_info release];
    _info = nil;
    _info = [info retain];
    
//    void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *) = ^(ALAsset *asset)
//    {
//        //获取经纬度以及拍照的时间
//        NSDictionary *metadata = asset.defaultRepresentation.metadata;
//        
//        NSDictionary *gpsdata = [metadata objectForKey:@"{GPS}"];
//        
//        self.lat = [[gpsdata valueForKey:@"Latitude"] doubleValue];
//        self.lng = [[gpsdata valueForKey:@"Longitude"] doubleValue];
//
//        NSDictionary *exif = [metadata objectForKey:@"{Exif}"];
//        self.photoDate =[exif objectForKey:@"DateTimeDigitized"];
//    };
//    
//    NSURL *assetURL = [info objectForKey:UIImagePickerControllerReferenceURL];
//    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
//    [library assetForURL:assetURL
//             resultBlock:ALAssetsLibraryAssetForURLResultBlock
//            failureBlock:^(NSError *error) {
//            }];
//    [library release];

    
    UIImage *oriImg = nil;
    if (_allowsImageEditing)
    {
        oriImg = [info valueForKey:UIImagePickerControllerEditedImage];
    }
    else
    {
        oriImg = [info valueForKey:UIImagePickerControllerOriginalImage];
    }
    
    CGSize clipSize = oriImg.size.width > oriImg.size.height ? UploadPhotoClipSizePor : UploadPhotoClipSizeLan;
    
    CGFloat r; // 缩小比例
    CGFloat hr = clipSize.width  / oriImg.size.width;
    CGFloat vr = clipSize.height / oriImg.size.height;
    r = MIN(hr, vr);
    r = MIN(1, r);
    CGSize newSize = CGSizeMake((int)(oriImg.size.width * r), (int)(oriImg.size.height * r));
    self.image = [oriImg transformWidth:newSize.width height:newSize.height rotate:YES];
    [self returnTheImage:self.image];
//
//    
//    UIImage *bdImage = [UIImage imageNamed:@"image_effect_selected_border.png"];
//    UIImageView *borderImage = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 59, 59)] autorelease];  //ytxtt
//    borderImage.image = bdImage;
//    borderImage.backgroundColor = [UIColor clearColor];
//    _borderImage = borderImage;
//    
//    BOOL addImageSuccess = YES;
//    if (UIImagePickerControllerSourceTypeCamera == picker.sourceType)
//    {
//        if (!_isFromSelfView)
//        {
//            UIImageWriteToSavedPhotosAlbum(_image, self, nil, nil);
//        }
//        
//        addImageSuccess = [self createImageScrollView:_image];
//        if (addImageSuccess) 
//        {
//            [self createNaviBar:YES];
//            [self createFilterBar];
//        }
//        else
//        {
//            TSAlert *alertStruct = [[[TSAlert alloc] init] autorelease];
//            alertStruct.isDismissByClick = YES;
//            alertStruct.alertMessage = kOpenImageFail;
//            alertStruct.alertStyleCode = TSAlertViewStyleNormalCode;
//            
//            [AppEngine.alertViewManager addAlertToArray:alertStruct];
//        }
//    }
//    else
//    {
//        addImageSuccess = [self createImageScrollView:_image];
//        if (addImageSuccess) 
//        {
//            [self createNaviBar:NO];
//            [self createFilterBar];
//        }
//        else
//        {
//            TSAlert *alertStruct = [[[TSAlert alloc] init] autorelease];
//            alertStruct.isDismissByClick = YES;
//            alertStruct.alertMessage = kOpenImageFail;
//            alertStruct.alertStyleCode = TSAlertViewStyleNormalCode;
//            
//            [AppEngine.alertViewManager addAlertToArray:alertStruct];
//        }
//    }  
    
}
- (void) returnTheImage:(UIImage *)image
{
    // Hold the image
    if ([_delegate respondsToSelector:@selector(returnImage:)])
    {
        [_delegate returnImage:image];
    }
    
    if ([_delegate respondsToSelector:@selector(returnImage:withInfo:)])
    {
        [_delegate returnImage:image withInfo:_info];
    }
    [_picker dismissViewControllerAnimatedWithCompatibility:YES];
    _picker.delegate = nil;
    [_picker release];
    _picker = nil;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
	// Remove the camera view from parent view
    [picker dismissViewControllerAnimatedWithCompatibility:YES];
//	isOriginalBar = NO;
//    [[LVFastLauncher sharedInstance] IOSFiveDefaultBackground];
	if ([_delegate respondsToSelector:@selector(cancelCamera)])
	{
		[_delegate cancelCamera];
	}
}


@end
